import 'dart:async';

import 'package:book_app/feature/devices/scan_screen.dart';
import 'package:book_app/feature/devices/view/note_card_widget.dart';
import 'package:book_app/feature/devices/view/note_detail_page.dart';
import 'package:book_app/product/db/devices_database.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter/material.dart';

import '../../product/models/device.dart';
import 'edit_devices_page.dart';


class HomeDevices extends StatefulWidget {
  const HomeDevices({super.key});

  @override
  State<HomeDevices> createState() => _HomeDevicesState();
}

class _HomeDevicesState extends State<HomeDevices> {
  late List<Device> devices;
  bool isLoading = false;
  final snackBarKeyA = GlobalKey<ScaffoldMessengerState>();
  final snackBarKeyB = GlobalKey<ScaffoldMessengerState>();
  final snackBarKeyC = GlobalKey<ScaffoldMessengerState>();
  final Map<DeviceIdentifier, ValueNotifier<bool>> isConnectingOrDisconnecting = {};
  BluetoothAdapterState _adapterState = BluetoothAdapterState.unknown;
  late StreamSubscription<BluetoothAdapterState> _adapterStateStateSubscription;

  @override
  void initState() {
    super.initState();
    _adapterStateStateSubscription = FlutterBluePlus.adapterState.listen((state) {
      _adapterState = state;
      setState(() {});
    });
    refreshDevices();
  }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(
      title: const Text(
        'Devices',
        style: TextStyle(fontSize: 24),
      ),
      actions: const [Icon(Icons.search), SizedBox(width: 12)],
    ),
    body: Center(
      child: isLoading
          ? const CircularProgressIndicator()
          : devices.isEmpty
          ? const Text(
        'No Devices',
        style: TextStyle(color: Colors.white, fontSize: 24),
      )
          : buildDevices(),
    ),
    floatingActionButton: FloatingActionButton(
      backgroundColor: Colors.black,
      child: const Icon(Icons.add),
      onPressed: () async {
        if( _adapterState == BluetoothAdapterState.on){
          //蓝牙开启
          await Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => const ScanScreen()),
          );
        }else{
          // EasyLoading.showError("蓝牙未开启");
          EasyLoading.showInfo("蓝牙未开启");
          print("蓝牙未开启");
        }
        refreshDevices();
      },
    ),
  );
  Widget buildDevices() => StaggeredGrid.count(
    // itemCount: notes.length,
    // staggeredTileBuilder: (index) => StaggeredTile.fit(2),
      crossAxisCount: 2,
      mainAxisSpacing: 2,
      crossAxisSpacing: 2,
      children: List.generate(
        devices.length,
            (index) {
          final device = devices[index];

          return StaggeredGridTile.fit(
            crossAxisCellCount: 1,
            child: GestureDetector(
              onTap: () async {
                await Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) => NoteDetailPage(noteId: device.id!),
                ));

                refreshDevices();
              },
              child: NoteCardWidget(device: device, index: index),
            ),
          );
        },
      ));

  @override
  void dispose() {
    _adapterStateStateSubscription.cancel();
    DevicesDatabase.instance.close();//关闭数据库
    super.dispose();
  }

  Future refreshDevices() async {
    setState(() => isLoading = true);
    devices = await DevicesDatabase.instance.readAllDevices();
    setState(() => isLoading = false);
  }
}
class BluetoothAdapterStateObserver extends NavigatorObserver {
  StreamSubscription<BluetoothAdapterState>? _adapterStateSubscription;

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    if (route.settings.name == '/DeviceScreen') {
      // Start listening to Bluetooth state changes when a new route is pushed
      _adapterStateSubscription ??= FlutterBluePlus.adapterState.listen((state) {
        if (state != BluetoothAdapterState.on) {
          // Pop the current route if Bluetooth is off
          navigator?.pop();
        }
      });
    }
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    // Cancel the subscription when the route is popped
    _adapterStateSubscription?.cancel();
    _adapterStateSubscription = null;
  }
}
